package com.financing.wap.util;

import java.security.Key;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.log4j.Logger;
  
/** 
 * 编码工具类 
 * @author lisu
 */   
public class QEncodeUtil {  
	static Logger logger = Logger.getLogger(QEncodeUtil.class);
	 //key 转换
	private static  Key key = null;
	static{
		try{
			KeyGenerator kgen = KeyGenerator.getInstance("AES");  
	        kgen.init(128);  
	        SecretKey secretKey = kgen.generateKey();
	        byte[] keyBytes = secretKey.getEncoded();
	        
	        //key 转换
	         key = new SecretKeySpec(keyBytes,"AES")	;
		}catch (Exception e){
			logger.error("QEncodeUtil init  key  error",e);
		}
		
	}
      
    public static void main(String[] args) throws Exception {  
        String content = "1|@|15000774677";  
        System.out.println("加密前：" + content);  
  
        String keyc = "qwer!@#$";  
        System.out.println("加密密钥和解密密钥：" + keyc);  
        String jiami = aesEncrypt(content,keyc);
        System.out.println(jiami);
        String jiemi = aesDecrypt(jiami, keyc);
        System.out.println(jiemi);
        
    }  
      
   
      
    /** 
     * AES加密 
     * @param content 待加密的内容 
     * @param encryptKey 加密密钥 
     * @return 加密后的byte[] 
     * @throws Exception 
     */  
    public static String aesEncrypt(String content, String encryptKey) throws Exception {
    	
        
        //加密 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
        cipher.init(Cipher.ENCRYPT_MODE, key);  
          
        byte[] returnData = cipher.doFinal(content.getBytes());  
        
        return Base64.encodeBase64String(returnData);
    }  
      
    /** 
     * AES解密 
     * @param encryptBytes 待解密的byte[] 
     * @param decryptKey 解密密钥 
     * @return 解密后的String 
     * @throws Exception 
     */  
    public static String aesDecryptByBytes(byte[] encryptBytes, String decryptKey) throws Exception {  
        
        //加密 
        Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");  
        cipher.init(Cipher.DECRYPT_MODE, key);  
        byte[] returnData = cipher.doFinal(encryptBytes);  
        return new String (returnData);
    }  
      
    public static String aesDecrypt(String encryptBytes, String decryptKey) throws Exception {
    	return aesDecryptByBytes(Base64.decodeBase64(encryptBytes),decryptKey);
    }
} 